package zjitc.servlet;

import com.fasterxml.jackson.databind.util.BeanUtil;
import org.apache.commons.beanutils.BeanUtils;
import zjitc.domain.User;
import zjitc.service.UserService;
import zjitc.service.UserServiceImpl;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        //设置编码
        request.setCharacterEncoding("utf-8");
        //获取数据
        HttpSession session = request.getSession();
        String checkCode = request.getParameter("verifycode");
        String checkcode_server = (String)session.getAttribute("CHECKCODE_SERVER");
        session.removeAttribute("CHECKCODE_SERVER");
        Map<String, String[]> map = request.getParameterMap();
        User user = new User();
        //封装User
        try {
            BeanUtils.populate(user,map);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
        //进行验证码校验
        if(!checkcode_server.equalsIgnoreCase(checkCode)){
            //验证码错误
            request.setAttribute("login_msg","验证码错误");
            //跳转到登录界面
            request.getRequestDispatcher("/login.jsp").forward(request,response);
            return;
        }
        //调用service查找
        UserService service = new UserServiceImpl();
        User loginUser = service.login(user);
        if(loginUser!=null){
            //登录成功
            session.setAttribute("user",loginUser);
            //重定向到check.jsp
            response.sendRedirect(request.getContextPath()+"/check.jsp");
        }else{
            //登录失败
            request.setAttribute("login_msg","用户名或密码错误");
            //跳转到登录页面
            request.getRequestDispatcher("/login.jsp").forward(request,response);
        }
    }
}
